package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /*
    * 添加新员工 姓名name重复问题
    * */
   @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'   ~[mysql-connector-java-8.0.30.jar:8.0.30]
        String message = ex.getMessage();
        //java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'lisi' for key 'idx_username'
        if (message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            String username=s[2];
            String msg =username+ MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }
        else return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

 /*  @ExceptionHandler
    public Result exceptionHandler(SQLSyntaxErrorException ex){
       // You have an error in your SQL syntax;
        String message = ex.getMessage();
        if (message.contains("You have an error in your SQL syntax;")){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }else return Result.error(MessageConstant.UNKNOWN_ERROR);
    } 是*/


}
